package io.paper.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.paper.entity.BeerMoldEntity;
import io.paper.service.BeerMoldService;
import io.paper.utils.CodeSetUtil;
import io.renren.controller.AbstractController;
import io.renren.utils.PageUtils;
import io.renren.utils.R;

/**
 * 系统用户
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月31日 上午10:40:10
 */
@RestController
@RequestMapping("/beer")
public class BeerMoldController extends AbstractController {
	@Autowired
	private BeerMoldService beerMoldService;
	
	private final static int WX_BILL_DETAIL_OFFSET = 1;
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat sdfFormt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat sdf_NUM = new SimpleDateFormat("yyyyMMdd");
    private static SimpleDateFormat TIME_ADF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    private static DecimalFormat df = new DecimalFormat("#0.00");
	
	/**
	 * 获取啤模信息
	 */
	@RequestMapping("/alllist")
	public R allInfo(){
		return R.ok().put("list", beerMoldService.queryBeerList());
	}
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	public R list(BeerMoldEntity param,Integer page, Integer limit){
		Map<String, Object> map = new HashMap<>();
		map.put("startRow", (page - 1) * limit+1);
		map.put("endRow", page* limit);
		map.put("para", param);
		//查询列表数据
		List<BeerMoldEntity> iqcSupplierBaseInfoTList = beerMoldService.queryList(map);
		int total = beerMoldService.queryTotal(map);
		
		PageUtils pageUtil = new PageUtils(iqcSupplierBaseInfoTList, total, limit, page);
		
		return R.ok().put("page", pageUtil);
	}
	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	//@RequiresPermissions("iqcsupplierbaseinfot:delete")
	public R delete(@RequestBody String[] bEERMOLDIDs){
		beerMoldService.deleteBatch(bEERMOLDIDs);
		
		return R.ok();
	}
	
	/**
	 * 新增
	 */
	@RequestMapping("/save")
	//@RequiresPermissions("iqcsupplierbaseinfot:delete")
	public R save(@RequestBody List<BeerMoldEntity> params){
		for(BeerMoldEntity parm:params){
			//判重
			beerMoldService.save(parm);
		}
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("/update")
	//@RequiresPermissions("iqcsupplierbaseinfot:delete")
	public R update(@RequestBody List<BeerMoldEntity> params){
		for(BeerMoldEntity parm:params){
			beerMoldService.update(parm);
		}
		return R.ok();
	}
	
	/**
	 * 导入啤模
	 */
	@RequestMapping("/importBeerMoldExcel")
	public R doImport(@RequestParam( value="file",required=false)MultipartFile file){
		Long currentUser=0L;
        Workbook wb = null;
        File excelFile = null;
        
        if(file != null){
            List multiList = null;
            try {
                if(file.equals("")||file.getSize()<=0){
                    file = null;
                }else {
                        InputStream ins = null;
                        ins = file.getInputStream();
                        excelFile = new File(file.getOriginalFilename());
                        CodeSetUtil.inputStreamToFile(ins, excelFile);
                        ins.close();
                }
                String path = excelFile.getPath();
                
                String fileType=path.substring(path.lastIndexOf(".")+1);
            	if("xlsx".equals(fileType.toLowerCase()) || "xls".equals(fileType.toLowerCase())){
            		wb = WorkbookFactory.create(excelFile);
            		//获取第一页
                    Sheet sheet = wb.getSheetAt(0);
                    //迭代每行记录
                    multiList = readExcel(sheet, currentUser);
                    if(wb != null){
                        wb.close();
                    }
            	}else{
            		return R.error("请导入 .xlsx 或 .xls 格式文件！");
            	}
                if(!excelFile.delete()){
                    logger.debug("临时文件删除失败");
                }
                List<BeerMoldEntity> list = (List) multiList.get(0);
                List<String> errorList = (List) multiList.get(1);
                if(list == null || list.size()==0){
                    return R.error("导入数据库0条");
                }
                if(errorList != null && errorList.size() > 0){
                    return R.error("数据错误").put("list", errorList);
                }
                Integer total = list.size() + errorList.size();
                Integer importCount = 0;
                String errorMsg = "";
                try{
                	importCount = beerMoldService.importBeerMold(list);
                }catch(Exception e){
                	errorMsg=e.getMessage();
                	logger.info(errorMsg);
                }
                if(!StringUtils.isEmpty(errorMsg)){
                	return R.error(errorMsg);
                }
                if(importCount > 0){
                	
                    Map<String, Object> map = new HashedMap();
                    map.put("total", total);
                    map.put("import", importCount);
                    return R.ok(map);
                } else {
                    return R.error("导入数据库0条");
                }
            } catch (Exception e){
                e.printStackTrace();
                if(wb != null){
                    try {
                        wb.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                if(!excelFile.delete()){
                    logger.debug("临时文件删除失败");
                }
                String message = null;
                if(e instanceof SQLException){
                    message = "数据库操作异常";
                } else {
                    message = "Excel模板有异常";
                }
                return R.error(message);
            }
        } else {
            return R.error("字段不可为空");
        }
    }
	
	public static String getValue(String[] item,int index){
        if(item.length > index){
            String value = item[index];
            if(!StringUtils.isEmpty(value) && value.startsWith("`")){
            	value=value.substring(1, value.length());
            }
            return value;
        }
        return "";
    }
	
	public static Date paseStringToDate(String timeStr){
		if(!StringUtils.isEmpty(timeStr)){
			try {
				Date date = sdfFormt.parse(timeStr);
				return date;
			}catch (java.text.ParseException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
    private List readExcel(Sheet sheet,Long userId){
        List<BeerMoldEntity> list = new ArrayList<>();
        List<String> errorList = new ArrayList<>();
        BeerMoldEntity dto = null;

        for( int i = WX_BILL_DETAIL_OFFSET; i <= sheet.getLastRowNum(); i++){
            Row row = sheet.getRow(i);
            if(row != null){
                dto = new BeerMoldEntity();
                String cellValue = null;
                //啤模编号
                row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                cellValue = CodeSetUtil.cellForString(row.getCell(0));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setBEERMOLDID(cellValue);
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:啤模编号有误",i+1));
                    }
                }
                //啤模名称
                row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                cellValue = CodeSetUtil.cellForString(row.getCell(1));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setBEERMOLDNAME(cellValue);
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:啤模名称有误",i+1));
                    }
                }
                //客户编号
                row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                cellValue = CodeSetUtil.cellForString(row.getCell(2));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setCUSTOMERID(cellValue);
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:客户编号有误",i+1));
                    }
                }
                //客户名称
                row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                cellValue = CodeSetUtil.cellForString(row.getCell(3));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setCUSTOMERCODE(cellValue);
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:客户名称有误",i+1));
                    }
                }
                //纸质
                row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                cellValue = CodeSetUtil.cellForString(row.getCell(4));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setQUALITY(cellValue);
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:纸质有误",i+1));
                    }
                }
                //用料(宽)
                cellValue = CodeSetUtil.cellForString(row.getCell(5));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setUSEWIDTH(Double.valueOf(cellValue));
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:用料(宽)有误",i+1));
                    }
                }
                //用料(长)
                cellValue = CodeSetUtil.cellForString(row.getCell(6));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setUSELENGTH(Double.valueOf(cellValue));
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:用料(长)有误",i+1));
                    }
                }
                //单位
                row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
                cellValue = CodeSetUtil.cellForString(row.getCell(7));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setUNITID(cellValue);
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:单位有误",i+1));
                    }
                }
                //单位比率
                cellValue = CodeSetUtil.cellForString(row.getCell(8));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setUNITEXCH(Double.valueOf(cellValue));
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:单位比率有误",i+1));
                    }
                }
                //一模成型数量
                cellValue = CodeSetUtil.cellForString(row.getCell(9));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setQUANTITY(Double.valueOf(cellValue));
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:一模成型数量有误",i+1));
                    }
                }
                //每箱用料比例
                row.getCell(10).setCellType(Cell.CELL_TYPE_STRING);
                cellValue = CodeSetUtil.cellForString(row.getCell(10));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setUNITQUANTITY(Integer.valueOf(cellValue));
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:每箱用料比例有误",i+1));
                    }
                }
                //存放位置
                row.getCell(11).setCellType(Cell.CELL_TYPE_STRING);
                cellValue = CodeSetUtil.cellForString(row.getCell(11));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setPLACE(cellValue);
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:存放位置有误",i+1));
                    }
                }
                //组件编号
                row.getCell(12).setCellType(Cell.CELL_TYPE_STRING);
                cellValue = CodeSetUtil.cellForString(row.getCell(12));
                if(StringUtils.hasText(cellValue)){
                    try {
                        dto.setPARENTBEERMOLDID(cellValue);
                    } catch (NumberFormatException e){
                        errorList.add(String.format("第%03d行:组件编号有误",i+1));
                    }
                }
                if(!StringUtils.isEmpty(dto.getBEERMOLDID())){
                    list.add(dto);
                }else{
                    errorList.add(String.format("第%03d行:啤模编号不能为空",i+1));
                }
            } else {
                errorList.add(String.format("%d行为空",i+1));
            }
        }

        return Arrays.asList(list, errorList);
    }
	
    
    /**
	 * 导出啤模
	 */
	@RequestMapping("/exportBeerMoldExcel")
	public void exportBeerMoldExcel(BeerMoldEntity param,HttpServletResponse response){
		Map<String, Object> map = new HashMap<>();
		map.put("para", param);
		String bEERMOLDID = param.getBEERMOLDID();
		logger.info(bEERMOLDID+"导出啤模："+map.toString());
		OutputStream out = null;
		boolean isExport = false;
		try {
			out = response.getOutputStream();// 取得输出流
			//设定输出文件头
			response.setContentType("application/vnd.ms-excel");// 定义输出类型
			response.setHeader("Content-Disposition","attachment;filename="+new String(("beerMold").getBytes("gbk"),"iso8859-1")+".xls");
			isExport = beerMoldService.exportBeerMoldExcel(map, out);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(out!=null){
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	
		logger.info("导出啤模："+isExport);
	}
}
